﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarvellousWorks.PracticalPatternNet8.Concept.Indexer;

/// <summary>
/// 提供单列字符串集合的多种索引访问方式。
/// 支持按索引、模糊字符串、精确字符串+索引三种方式访问集合元素。
/// </summary>
public class SingleColumnCollection
{
    /// <summary>
    /// 静态只读的国家/地区名称集合。
    /// </summary>
    private static readonly string[] countries = new string[]
    {
        "china","chile","uk","chicago","chicago bears",
    };

    /// <summary>
    /// 通过整数索引访问集合中的元素。
    /// </summary>
    /// <param name="index">元素的索引。</param>
    /// <returns>指定索引的字符串。</returns>
    /// <exception cref="IndexOutOfRangeException">索引超出范围时抛出。</exception>
    public string this[int index]
    {
        get
        {
            if (index < 0 || index >= countries.Length)
            {
                throw new IndexOutOfRangeException("Index out of range");
            }
            return countries[index];
        }
    }

    /// <summary>
    /// 通过字符串模糊查找集合中所有包含指定子串的元素。
    /// </summary>
    /// <param name="name">要查找的子串（不区分大小写）。</param>
    /// <returns>所有包含指定子串的元素数组。</returns>
    /// <exception cref="ArgumentNullException">name 为空或 null 时抛出。</exception>
    public string[] this[string name]
    {
        get
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name), "Name cannot be null or empty");
            }
            return countries.Where(c => c.Contains(name, StringComparison.OrdinalIgnoreCase)).ToArray();
        }
    }

    /// <summary>
    /// 通过字符串精确查找集合中所有与指定字符串完全匹配的元素，并按索引返回。
    /// </summary>
    /// <param name="name">要精确匹配的字符串（不区分大小写）。</param>
    /// <param name="index">匹配结果中的索引。</param>
    /// <returns>匹配的字符串。</returns>
    /// <exception cref="ArgumentNullException">name 为空或 null 时抛出。</exception>
    /// <exception cref="KeyNotFoundException">未找到匹配项时抛出。</exception>
    /// <exception cref="IndexOutOfRangeException">index 超出匹配项范围时抛出。</exception>
    public string this[string name, int index]
    {
        get
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name), "Name cannot be null or empty");
            }
            // 查找所有精确匹配项
            var matches = countries
                .Select((c, i) => new { Value = c, Index = i })
                .Where(x => x.Value.Equals(name, StringComparison.OrdinalIgnoreCase))
                .ToList();

            if (matches.Count == 0)
            {
                throw new KeyNotFoundException($"No element found matching '{name}'.");
            }
            if (index < 0 || index >= matches.Count)
            {
                throw new IndexOutOfRangeException("Index out of range for matched elements.");
            }
            return matches[index].Value;
        }
    }
}
